import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// axios.defaults.withCredentials = true;// 允许跨域携带cookie

// 创建一个axios实例, 这个实例有请求拦截的校验
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000  // 请求超五秒判断为超时
})
// 请求拦截
service.interceptors.request.use(config => {
  if (store.getters.token) {
    // config.headers['X-Token'] = getToken()
    config.headers['token'] = getToken()
  }
  return config
}, error => {
  // 请求错误时做的事情
  // return Promise.reject(error)
  return Promise.reject('请求超时')
})

// 响应拦截   如果您想获得http信息，如头信息或状态  return  response => response
service.interceptors.response.use(response => {
  const res = response.data
  if (res.code != 0 && res.code != -4) {
    // Message({
    //   message:  '网络响应错误' || res.msg || 'Error',
    //   type: 'error',
    //   duration: 4 * 1000
    // })
    return Promise.reject(new Error(res.message || 'Error'))
  }
  else {
    return res
  }
},
error => {
  Message({
    message: '网络响应错误!' || error.message,
    type: 'error',
    duration: 4 * 1000
  })
  return Promise.reject(error)
}
)

// 2 这个axios实例 没有请求拦截 token的校验
export const unimpeded = axios.create({
  timeout: 10000
})
unimpeded.interceptors.request.use(config => {
  return config
})

unimpeded.interceptors.response.use(response => {
  const res = response.data
  return res
})

export default service
